package com.example.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisService<T> {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 默认时间是一天(单位：分钟)
     */
    private static final long MINUTES_OF_ONE_DAY = 24* 60;

    /**
     * 将key/value 存放到redis数据库，默认失效时间是一天
     * @param key
     * @param value
     */
    public void set(String key, T value){
        set(key, value, MINUTES_OF_ONE_DAY);
    }

    /**
     * 将key/value 存放到redis数据库，可自定义失效时间（单位:分钟）
     * @param key
     * @param value
     */
    public void set(String key, T value, long expireTime){
        ValueOperations<String, T> valueOperations = redisTemplate.opsForValue();
        valueOperations.set(key, value, expireTime, TimeUnit.MINUTES);
    }

    /**
     * 判断key是否存在于redis数据库
     * @param key
     * @return
     */
    public boolean exists(final String key){
        return redisTemplate.hasKey(key);
    }

    /**
     * 获取key对应的键值
     * @param key
     * @return
     */
    public T get(String key){
        ValueOperations<String, T> valueOperations = redisTemplate.opsForValue();
        return valueOperations.get(key);
    }

    /**
     * 获取key对应的键值,并更新失效时间
     * @param key
     * @return
     */
    public T getAndUpdateTime(String key){
        T result = get(key);
        if(result != null){
            set(key, result);
        }
        return result;
    }

    /**
     * 删除redis数据库中对应的key
     * @param key
     */
    public void delete(String key){
        redisTemplate.delete(key);
    }
}
